/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.*;
import java.util.regex.Pattern;

/**
 *
 * @author Dung Doan
 */
public class OrderBy {
    public OrderBy()
    {
        
    }
    
    public static Boolean hasOrderBy(String root)
    {
        String query = root.toUpperCase();
        if (query.indexOf("ORDER BY") < 0)
            return false;
        return true;
    }
    public static String getOrderBy(String root)
    {
        String query = root.toUpperCase();
        int beginIndex = 0;
        int endIndex = query.indexOf("SELECT");
        if (endIndex < beginIndex)
            return null;
        beginIndex = endIndex + 6;
        
        
        endIndex = query.indexOf("FROM", beginIndex);
        if (endIndex < beginIndex)
            return null;
        
        beginIndex = endIndex + 4;
        endIndex = query.indexOf("WHERE", beginIndex);
        if (endIndex > beginIndex)
            beginIndex = endIndex + 5;
        
        endIndex = query.indexOf("GROUP BY", beginIndex);
        if (endIndex > beginIndex)
            beginIndex = endIndex + 8;
        
        endIndex = query.indexOf("HAVING", beginIndex);
        if (endIndex > beginIndex)
            beginIndex = endIndex + 6;
        
        endIndex = query.indexOf("ORDER BY", beginIndex);
        if (endIndex < beginIndex)
            return null;
        
        beginIndex = endIndex + 8;
        
        return root.substring(beginIndex).trim();
        

        
    }
    
    
    public static List<OrderByType> ParseOrderBy(String query)
    {
        if (hasOrderBy(query) == false)
            return null;
        ArrayList<OrderByType> list = new ArrayList<OrderByType>();
        String orderByString = getOrderBy(query);
        
        
        String REGEX = ",";
        Pattern p = Pattern.compile(REGEX);
        String[] items = p.split(orderByString);
        for (int i = 0 ; i < items.length ; i++)
            list.add(new OrderByType(items[i].trim()));
        return list;
    }
    
}
